import treeDao from "../dao/tree";
import {Notice, Tree} from "../types";
import {getUuid,getCurrentTime,logger} from "../utils";
import groupService from "./group";

export async function queryList(groupId) {
    try {
        return await treeDao.queryList(groupId);
    } catch (error) {
        logger(error);
    }
}

export async function insert(data:Tree){
    try {
        const rank = await treeDao.getRank()
        if(data.risk){
           await groupService.update({id:data.groupId,status:1})
        }
        return await treeDao.insert({ ...data, id: getUuid(),createTime:getCurrentTime(),rank});
    } catch (error) {
        logger(error);
    }
}

export async function deleteById(id){
    try {
        return await treeDao.deleteById(id);
    } catch (error) {
        logger(error);
    }
}

export async function update(data :Tree){
    try {
        const tree = await treeDao.update(data)
        await updateGroupRisk(data.groupId)
        return tree;
    } catch (error) {
        logger(error);
    }
}
export async function queryById(id){
    try {
        return await treeDao.queryById(id);
    } catch (error) {
        logger(error);
    }
}

async function updateGroupRisk(id){
    const treeList = await queryList(id)
    let risk = 0
    for (let i = 0; i < treeList.length; i++) {
        if(treeList[i].risk){
            risk = 1
            break
        }
    }
    await groupService.update({id,status:risk})
}

async function queryNoticeNum() {
    try {
        const treeList = await treeDao.queryNotice()
       return treeList.length
    } catch (error) {
        logger(error);
    }
}
export default {
    queryList,
    insert,
    deleteById,
    update,
    queryById,
    queryNoticeNum
};
